package dk.dtu.student.assignmentfour;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import android.app.Activity;
import android.app.Application;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.Contacts;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.util.SparseArray;

public class MyApplication extends Application {

	public static final Uri SMS_CONTENT_URI = Uri.parse("content://sms");
	public List<SmsThread> mSmsThreads;
	private static HashMap<String, String> mContactInfo = new HashMap<String, String>();
	private static Cursor mSmsCursor;
	
	public static String getPersonName(Context context, String phoneNumber) {
		if (mContactInfo.size() == 0)
		{
			Cursor mPersonCursor = context.getContentResolver()
				    .query(Contacts.CONTENT_URI, null, null, null, null);
			
			if (mPersonCursor.getCount() > 0) {
				while (mPersonCursor.moveToNext()) {
					String _id = mPersonCursor.getString(mPersonCursor.getColumnIndex(Contacts._ID));
					String name = mPersonCursor.getString(mPersonCursor.getColumnIndex(Contacts.DISPLAY_NAME));
					
					if (Integer.parseInt(mPersonCursor.getString(
							mPersonCursor.getColumnIndex(Contacts.HAS_PHONE_NUMBER))) > 0) {
						 Cursor pCur = context.getContentResolver().query(
						           CommonDataKinds.Phone.CONTENT_URI,
						           null,
						           CommonDataKinds.Phone.CONTACT_ID +" = ?",
						           new String[]{_id}, null);
						 while (pCur.moveToNext()) 
						 {
						     String phoneNo = pCur.getString(pCur.getColumnIndex(CommonDataKinds.Phone.NUMBER));
						     //Log.v("getPersonName", "" + name + ": " + phoneNo);
						     mContactInfo.put(phoneNo.replace("+", "").replace(" ", "").toLowerCase().trim(), name);
						 }
	                     pCur.close();
					}
				}
			}
			mPersonCursor.close();
		}
		
		String n = mContactInfo.get(phoneNumber);
		if (null != n)
			return n;
		
		Set<Entry<String, String>> set = mContactInfo.entrySet();
	    Iterator<Entry<String, String>> i = set.iterator();

	    while(i.hasNext()){
	      Entry<String, String> me = i.next();
	      //Log.v("getPersonName", "" + me.getKey() + " vs. " + phoneNumber.replace("+", "").toLowerCase().trim());
	      if (me.getKey().contains(phoneNumber.replace("+", "").toLowerCase().trim()) ||
	    		  phoneNumber.replace("+", "").toLowerCase().trim().contains(me.getKey()))
	    	  return me.getValue();
	    }
        return PhoneNumberUtils.formatNumber(phoneNumber);
	}
    
    public List<SmsThread> getAllSms(Activity context) {
        List<SmsThread> threads = new ArrayList<SmsThread>();
        Uri message = SMS_CONTENT_URI;
        ContentResolver cr = context.getContentResolver();
        
        if (null == mSmsCursor)
        	mSmsCursor = cr.query(message, null, null, null, null);
        else
        	mSmsCursor.requery();
        int totalSMS = mSmsCursor.getCount();

        SmsMessage sms = null;
        SmsThread thread = null;
        if (mSmsCursor.moveToFirst()) {
            for (int i = 0; i < totalSMS; i++) {
            	String messageId = mSmsCursor.getString(mSmsCursor.getColumnIndexOrThrow("_id"));
            	String threadId = mSmsCursor.getString(mSmsCursor.getColumnIndexOrThrow("thread_id"));
            	String address = mSmsCursor.getString(mSmsCursor.getColumnIndexOrThrow("address")).replace(" ",  "");
            	String body = mSmsCursor.getString(mSmsCursor.getColumnIndexOrThrow("body"));
            	String date = mSmsCursor.getString(mSmsCursor.getColumnIndexOrThrow("date"));
            	boolean mine;
            	if (mSmsCursor.getString(mSmsCursor.getColumnIndexOrThrow("type")).contains("1")) {
                    mine = false;
                } else {
                    mine = true;
                }
            	boolean existing = false;
            	for (SmsThread t : threads)
            	{
            		if (t.getThreadId().equals(threadId))
            		{
            			thread = t;
            			existing = true;
            		}
            	}
            	
            	if (null == thread)
            		thread = new SmsThread(threadId, address, getPersonName(context, address));
            	
            	sms = new SmsMessage(body, messageId, date);
            	sms.setIfMine(mine);
            	
            	thread.addSmsMessage(sms);
            	if (!existing)
            		threads.add(thread);
                
                thread = null;
                mSmsCursor.moveToNext();
            }
        }

        return threads;
    }
    
    @Override
	public void onTerminate() {
    	if (null != mSmsCursor)
    	{
    		mSmsCursor.close();
    		mSmsCursor = null;
    	}
    	
		super.onTerminate();
	}
}
